from flask import Flask, render_template
from flask_socketio import SocketIO, emit
import time
from threading import Lock

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

# 倒计时状态
timer_state = {
    'running': False,
    'remaining_time': 0,
    'last_update': time.time(),
    'player_turn': 1  # 当前轮到哪个玩家 (1, 2 或 3)
}

# 线程锁
thread_lock = Lock()

# 默认倒计时时间（秒）
DEFAULT_TIME = 180

def background_timer():
    """后台计时线程"""
    while True:
        with thread_lock:
            if timer_state['running']:
                current_time = time.time()
                elapsed = current_time - timer_state['last_update']
                timer_state['remaining_time'] -= elapsed
                timer_state['last_update'] = current_time
                
                if timer_state['remaining_time'] <= 0:
                    timer_state['remaining_time'] = 0
                    timer_state['running'] = False
                    socketio.emit('timer_end', {'player': timer_state['player_turn']})
                
                # 广播当前时间给所有客户端
                socketio.emit('timer_update', {
                    'remaining_time': int(timer_state['remaining_time']),
                    'player_turn': timer_state['player_turn']
                })
        socketio.sleep(1)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect')
def handle_connect():
    # 新客户端连接时发送当前状态
    emit('timer_update', {
        'remaining_time': int(timer_state['remaining_time']),
        'player_turn': timer_state['player_turn']
    })

@socketio.on('start_timer')
def handle_start_timer(data):
    with thread_lock:
        if not timer_state['running']:
            timer_state['running'] = True
            timer_state['last_update'] = time.time()
            if 'initial_time' in data:
                timer_state['remaining_time'] = data['initial_time']
            emit('timer_started', {
                'remaining_time': int(timer_state['remaining_time']),
                'player_turn': timer_state['player_turn']
            }, broadcast=True)

@socketio.on('pause_timer')
def handle_pause_timer():
    with thread_lock:
        if timer_state['running']:
            timer_state['running'] = False
            emit('timer_paused', broadcast=True)

@socketio.on('reset_timer')
def handle_reset_timer(data):
    with thread_lock:
        timer_state['running'] = False
        timer_state['remaining_time'] = data.get('initial_time', DEFAULT_TIME)
        timer_state['player_turn'] = data.get('player_turn', 1)
        emit('timer_reset', {
            'remaining_time': int(timer_state['remaining_time']),
            'player_turn': timer_state['player_turn']
        }, broadcast=True)

@socketio.on('switch_player')
def handle_switch_player(data):
    with thread_lock:
        new_player = data.get('player', 1)
        if 1 <= new_player <= 3:
            timer_state['player_turn'] = new_player
            emit('player_switched', {
                'player_turn': timer_state['player_turn']
            }, broadcast=True)

if __name__ == '__main__':
    # 初始化倒计时
    timer_state['remaining_time'] = DEFAULT_TIME
    # 启动后台线程
    socketio.start_background_task(background_timer)
    socketio.run(app, debug=True)